package cn.com.customer.manager.ui.order.list

import android.app.DatePickerDialog
import android.content.Intent
import android.view.View
import android.widget.DatePicker
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.com.customer.manager.Constants
import cn.com.customer.manager.R
import cn.com.customer.manager.adapter.OrderListAdapter
import cn.com.customer.manager.base.BaseFragment
import cn.com.customer.manager.bean.Order
import cn.com.customer.manager.bean.OrderListInfo
import cn.com.customer.manager.bean.RequestOrder
import cn.com.customer.manager.ui.order.addOrder.AddOrderActivity
import cn.com.customer.manager.ui.order.detail.OrderDetailActivity
import com.chad.library.adapter.base.BaseQuickAdapter
import com.xuexiang.xui.utils.ResUtils
import com.xuexiang.xui.widget.actionbar.TitleBar
import com.xuexiang.xui.widget.searchview.MaterialSearchView
import com.xuexiang.xutil.data.DateUtils
import com.xuexiang.xutil.display.BarUtils
import kotlinx.android.synthetic.main.fragment_data_query.*
import java.util.*


/**
 * 订单
 */
class OrderFragment : BaseFragment(), BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener, OrderContract.View ,DatePickerDialog.OnDateSetListener {
    private var mPresenter: OrderContract.Presenter = OrderPresenter(this)
    private lateinit var mAdapter: OrderListAdapter
    var page: Int = 1
//    private val mHeaders = arrayOf("订单状态", "支付方式")
////    private val mPopupViews: MutableList<View> = mutableListOf()
////    private var mStateAdapter: ListDropDownAdapter? = null
////    private var mPayWayAdapter: ListDropDownAdapter? = null
    private lateinit var states: Array<String>
    private var startTime=DateUtils.date2String(DateUtils.nMonthsAfterToday(-1),DateUtils.yyyyMMdd.get())
    private var endTime=DateUtils.getNowString(DateUtils.yyyyMMdd.get())
    private lateinit var payWays: Array<String>
    private var dialogType=0
    private var mSearchText = "";
    private var mType = 1
    private var mRealSearchData: MutableList<Order> = mutableListOf()
    private var mData: MutableList<Order> = mutableListOf()
    override fun getLayoutId(): Int = R.layout.fragment_data_query

    override fun initView() {
        order_title.addAction(object : TitleBar.ImageAction(R.drawable.ic_action_search) {
            override fun performAction(view: View?) {
                order_search_view.showSearch()
            }

        })
        BarUtils.addMarginTopEqualStatusBarHeight(order_search_view)
        order_search_view.setVoiceSearch(false)
        order_search_view.setEllipsize(true)
        order_search_view.setBackgroundResource(R.color.bg_color)
      order_search_view.setSuggestions( ResUtils.getStringArray(R.array.state_entry))
        order_search_view.setOnQueryTextListener(object : MaterialSearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                onQueryResult(query)
                mSearchText = ""
                return false
            }

            override fun onQueryTextChange(newText: String): Boolean { //Do some magic
                mSearchText = newText
                if(mSearchText!=null){
                    requestData()
                }
                return false
            }
        })
        order_search_view.setOnSearchViewListener(object : MaterialSearchView.SearchViewListener {
            override fun onSearchViewShown() {
                mType = 0//Do some magic
            }

            override fun onSearchViewClosed() {
                mType = 1//Do some magic
                mSearchText = ""//Do some magic
            }
        })
        order_search_view.setSubmitOnClick(true)
        initRv()
        requestData()
        order_startTime.setOnClickListener(this)
        order_endTime.setOnClickListener(this)
        iv_add_order.setOnClickListener(this)
    }
    var suggestions: MutableList<String> = mutableListOf()
    private fun onQueryResult(query: String) {
        var item=mRealSearchData[suggestions.indexOf(query)]
        startActivity(Intent(activity, OrderDetailActivity::class.java).putExtra("orderId", item.orderId))
    }

    //  fun init(){
//      //init age menu
//      //init age menu
//      val stateView = ListView(context)
//      stateView.dividerHeight = 0
//      mStateAdapter = ListDropDownAdapter(context, states)
//      stateView.adapter = mStateAdapter
//
//      //init sex menu
//      //init sex menu
//      val payWayView = ListView(context)
//      payWayView.dividerHeight = 0
//      mPayWayAdapter = ListDropDownAdapter(context, payWays)
//      payWayView.adapter = mPayWayAdapter
//
//      //init mPopupViews
//      mPopupViews.add(stateView)
//      mPopupViews.add(payWayView)
//      //add item click event
//      stateView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
//          mStateAdapter!!.selectPosition = position
//          order_ddMenu.setTabMenuText(if (position == 0) mHeaders[0] else states[position])
//          order_ddMenu.closeMenu()
//      }
//      payWayView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
//          mPayWayAdapter!!.selectPosition = position
//          order_ddMenu.setTabMenuText(if (position == 0) mHeaders[1] else payWays[position])
//          order_ddMenu.closeMenu()
//      }
//
//      //init dropdownview
//      order_ddMenu.setDropDownMenu(mHeaders, mPopupViews, recycleview_order)
//      iv_add_order.setOnClickListener(this)
//
//  }
private  fun showDateDialog(): Unit {
    val calendar: Calendar = Calendar.getInstance()
    //构建一个日期对话框，该对话框已经集成了日期选择器
//DatePickerDialog的第二个构造参数指定了日期监听器
    val dialog = DatePickerDialog(activity, this,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH))
    //把日期对话框显示在界面上
    dialog.show()
}
    override
    fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        if (dialogType === 0) {
            startTime = String.format("%d-%d-%d", year, month + 1, dayOfMonth)
            order_startTime.text = startTime
        } else {
            endTime = String.format("%d-%d-%d", year, month + 1, dayOfMonth)
            order_endTime.text = endTime
        }
    }
    override fun onClick(v: View?) {
        super.onClick(v)
        when (v) {
            iv_add_order -> {
                startActivity(Intent(activity, AddOrderActivity::class.java).putExtra("customerId", "").putExtra("name",""))

            }
            order_startTime -> {
             dialogType=0
                showDateDialog()
            }
            order_endTime -> {
            dialogType=1
                showDateDialog()
            }
        }
    }

    private fun requestData() {
    var params=RequestOrder("",startTime,endTime,mSearchText,"","",page.toString(),Constants.PAGE_SIZE.toString())
       mPresenter.getList(params)
    }

    private fun initRv() {
        order_rv.layoutManager = LinearLayoutManager(mContext, RecyclerView.VERTICAL, false)
        mAdapter = OrderListAdapter(R.layout.item_order_list)
        order_rv.adapter = mAdapter
        mAdapter.onItemClickListener = this
        mAdapter.setOnLoadMoreListener(this, order_rv)

    }

    override fun onLoadMoreRequested() {
        page++
        requestData()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        startActivity(Intent(activity, OrderDetailActivity::class.java).putExtra("orderId",  mData[position].orderId))
    }

    override fun onDestroyView() {
//        sticky_container.recycle()
        if (order_search_view.isSearchOpen) {
            order_search_view.closeSearch()
        }
        super.onDestroyView()
    }

    override fun setList(data: OrderListInfo) {
        if (mType == 1) {
            orderList(data)
        } else {
            initSearchData(data)
        }
    }
    private fun initSearchData(data: OrderListInfo) {
        suggestions.clear()
        mRealSearchData.clear()
         mRealSearchData.addAll(data.orders)
          mRealSearchData.forEach {
                suggestions.add(it.orderName)
        }
        order_search_view.setSuggestions(suggestions.toTypedArray())
    }
    private fun orderList(data: OrderListInfo) {
        if (page == 1) {
            mAdapter.setNewData(data.orders)
            mData.clear()
            mData= data.orders as MutableList<Order>
        } else {
            mAdapter.addData(data.orders)
            mData.addAll(data.orders as MutableList<Order>)
        }
        if (mAdapter.isLoadMoreEnable and mAdapter.isLoading) {
            mAdapter.loadMoreComplete()
        }
        if (data.orders.size<Constants.PAGE_SIZE){
            mAdapter.loadMoreEnd()
        }
    }

    override fun setPresenter(presenter: OrderContract.Presenter) {
        mPresenter = presenter
    }


}